<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\model\Acct;
use app\common\model\Acctapply;
use app\common\model\Channelapply;
use app\common\model\Admin;
use app\common\model\Applyinfo;
use app\common\model\Area;
use app\common\model\Custom;
use app\common\model\shop\Goods;
use app\common\model\shop\Order;
use app\common\model\User as ModelUser;
use app\common\model\user\Apply;
use app\common\model\user\Channel;
use app\common\model\user\Commission;
use app\common\model\user\Level;
use think\Config;
use think\Env;
use think\Log;
use think\Validate;

use function Complex\abs;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'real_user', 'apply_channel', 'add_apply'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        // 获取当前用户基本信息
        $userId = $this->auth->id;
        $user = ModelUser::with('userLevel')->find($userId);

        // 获取必要的配置项
        $effectivePerformance = Config('site.effective_performance');
        $monthNum = config('site.month_num') ?? 1;

        // 提取常用条件
        $acctId = $user->acct_id;
        $channelLevel = $user->channel_level;

        // 并行查询不相关的数据，减少等待时间
        $channelName = ModelUser::where('id', $user->channel)->where('is_channel', 1)->value('nickname');
        $todayPerformance = Order::where('user_id', $userId)->where('status', '99')->whereTime('finished_time', 'today')->sum('total_fee');
        $user['total_performance'] = Order::where('user_id', $userId)->where('status', '99')->sum('total_fee');

        $directSubordinateCount = ModelUser::where('parent_id', $userId)->count();
        $levelUserIds = $user['level_id'] > 0 ?
            ModelUser::where('level_id', $user['level_id'])->column('id') : [];

        // 计算会员等级相关信息
        $lastLevelInfo = Level::where('team_num', '<=', $directSubordinateCount)
            ->where('last_month_ach', '<=', $user['month'])
            // ->where('acct_id', $acctId)
            ->order('team_num desc')
            ->find();

        $levelInfo = $lastLevelInfo ?
            Level::where('last_month_ach', '>', $lastLevelInfo['last_month_ach'])
            // ->where('acct_id', $acctId)
            ->order('last_month_ach asc')
            ->find() :
            Level::order('last_month_ach asc')->find();

        // 设置等级相关属性
        if ($user['level_id'] > 0) {
            $user['parent_level'] = $lastLevelInfo ? $lastLevelInfo['name'] : 'S1';
            $sameLevelUserIds = $lastLevelInfo ?
                ModelUser::where('level_id', $lastLevelInfo['id'])->column('id') :
                ModelUser::where('level_id', 0)->column('id');
        } else {
            $user['parent_level'] = 'S*';
            $sameLevelUserIds = [];
        }

        // 计算团队和佣金相关数据
        $user['channel_name'] = $channelName;
        $user['today'] = $todayPerformance;
        $user['last_month_level'] = $lastLevelInfo ? $lastLevelInfo['name'] : '';
        $user['parent_month'] = !empty($sameLevelUserIds) ?
            Order::whereIn('user_id', $sameLevelUserIds)
            ->where('status', '>', '0')
            ->whereTime('pay_time', 'month')
            ->sum('total_fee') : 0;
        $user['level_num'] = count($levelUserIds);

        // 计算升级所需数据
        $requiredTeamMembers = $lastLevelInfo ? $lastLevelInfo->team_num - $directSubordinateCount : 0;
        $requiredPerformance = $levelInfo ? bcsub($levelInfo->last_month_ach, $user['month'], 2) : 0;
        $user->people = max(0, $requiredTeamMembers);
        $user->balance = max(0, $requiredPerformance);
        $user->level_info = $levelInfo;

        // 计算佣金数据
        $commissionData = [
            'fx' => 0,
            'level' => 0
        ];
        if ($userId) {
            $commissionResults = Commission::where('user_id', $userId)
                ->whereIn('type', ['fx', 'level'])
                ->field('type, sum(money) as total_money')
                ->group('type')
                ->select();

            foreach ($commissionResults as $result) {
                $commissionData[$result['type']] = $result['total_money'];
            }
        }

        $user['commission'] = $commissionData['fx'];
        $user['level_commission'] = $commissionData['level'];

        // 获取父级和账户信息
        $user['parent'] = $user['parent_id'] ? ModelUser::get($user['parent_id']) : null;

        $acct = Acct::get($acctId);
        $admin = $acct && $acct->admin_id ? Admin::get($acct->admin_id) : null;
        $user['acct_name'] = $admin ? $admin->nickname : '';

        // 计算直接下线和团队业绩
        $directSubordinateIds = ModelUser::where('parent_id', $userId)->column('id');

        // 有效业绩人员统计
        $effectivePersons = [];
        if (!empty($directSubordinateIds)) {
            $effectivePersons = collection(Order::whereIn('user_id', $directSubordinateIds)
                ->where('status', '99')
                ->group('user_id')
                ->field('user_id, sum(pay_fee) as total_pay_fee')
                ->having("total_pay_fee>{$effectivePerformance}")
                ->select())->toArray();
        }
        $user['persons'] = count($effectivePersons);
        $user['team_performance'] = !empty($directSubordinateIds) ?
            Order::whereIn('user_id', $directSubordinateIds)
            ->where('status', '99')
            ->sum('pay_fee') : 0;

        // 计算渠道相关数据
        $channelStats = [
            'total' => 0,
            'level1' => 0,
            'level2' => 0,
            'level3' => 0
        ];

        $channelLevelIds = [];
        $channelWhere = ['channel' => $userId, 'is_channel' => 1];

        $channelStats['total'] = ModelUser::where($channelWhere)->count();
        $channelStats['level1'] = ModelUser::where($channelWhere)->where('channel_level', 1)->count();
        $channelStats['level2'] = ModelUser::where($channelWhere)->where('channel_level', 2)->count();
        $channelStats['level3'] = ModelUser::where($channelWhere)->where('channel_level', 3)->count();
        $channelLevelIds = ModelUser::where($channelWhere)->column('id');

        $user['channel_num'] = $channelStats['total'];
        $user['channel_level_1'] = $channelStats['level1'];
        $user['channel_level_2'] = $channelStats['level2'];
        $user['channel_level_3'] = $channelStats['level3'];

        // 计算渠道佣金
        $user['channel_level_commission'] = !empty($channelLevelIds) ?
            Commission::whereIn('user_id', $channelLevelIds)
            ->where('status', '1')
            ->where('type', 'channel')
            ->sum('source_price') : 0;

        // 处理不同渠道级别的数据
        $totalPerformance = 0;
        $channel = null;

        switch ($channelLevel) {
            case 0:
                $channel = Channel::get(1);
                $user['direct_num'] = $channel ? $channel['direct_num'] - $user['persons'] : 0;
                $pids = ModelUser::whereIn('parent_id', [$userId])->column('id');
                $totalPerformance = !empty($pids) ?
                    Order::whereIn('user_id', $pids)
                    ->where('status', '99')
                    ->sum('total_fee') : 0;
                break;
            default:
                $channel = Channel::get($channelLevel + 1);
                $user['direct_num'] = $channel ? $channel['direct_num'] - $channelStats['total'] : 0;
                // 使用优化后的迭代方法替代递归
                $ids = ModelUser::getAllSubordinates($channelLevelIds);
                $totalPerformance = !empty($ids) ?
                    Commission::whereIn('user_id', $ids)
                    ->where('status', '1')
                    ->where('type', 'channel')
                    ->sum('source_price') : 0;
                break;
        }

        $user['team_ach'] = $channel && $totalPerformance ? bcsub($channel['team_ach'], $totalPerformance, 2) : 0;

        // 计算连续未达标月份数
        $teamTurnover = Channel::where('id', $channelLevel)->value('reduce_rules');
        $monthNumber = 0;
        $allSubordinateIds = ModelUser::getAllSubordinates([$userId]);

        if (!empty($allSubordinateIds) && $teamTurnover) {
            for ($i = 1; $i <= $monthNum; $i++) {
                $startDay = date('Y-m-1', strtotime("-{$i} month"));
                $endDay = date('Y-m-t 23:59:59', strtotime("-{$i} month"));

                $monthlyPerformance = Order::whereIn('user_id', $allSubordinateIds)
                    ->where('status', '99')
                    ->whereTime('finished_time', 'between', [$startDay, $endDay])
                    ->sum('total_fee');

                if ($monthlyPerformance >= $teamTurnover) {
                    $monthNumber = 0;
                    break;
                }

                $monthNumber++;
            }
        }

        $user['month_number'] = $monthNumber;
        $this->success('', $user);
    }

    /**
     * 会员登录
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     * @param string $code 小程序登录CODE
     * @param string $type 1=用户,2=经销商
     */

    public function mobilelogin()
    {
        $post = $this->request->post();
        extract($post);
        if (!$mobile || !$captcha) {
            $this->error(__('参数错误'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号格式错误'));
        }
        if (!Sms::check($mobile, $captcha, 'default') && $captcha != 8888) {
            $this->error(__('验证码错误'));
        }
        $user = \app\common\model\User::getByMobile($mobile);

        if ($user) {
            if ($type == 1 && $user['is_channel'] == 1) {
                // $this->error(__('请登陆经销商端'));
            }
            if ($type == 2 && $user['is_channel'] == 0) {
                $this->error(__('您还不是经销商无法登陆'));
            }
            if ($user->status != 'normal') {
                $this->error(__('未达到有效销售订单数量'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $this->error('手机号非内部账号，不能登录');

            // $ret = $this->auth->register($nickname ?? '', Random::alnum(), $mobile);
        }
        $url = "https://api.weixin.qq.com/sns/jscode2session?";
        $appid = Env::get('wx.appid');
        $appsecret = Env::get('wx.appsecret');


        $param = array(
            "appid" => $appid,
            "secret" => $appsecret,
            "js_code" => $code,
            "grant_type" => "authorization_code"
        );

        $client = new \GuzzleHttp\Client();

        $response = $client->get($url, [
            'query' => $param
        ]);
        $res = $response->getBody();

        $res = json_decode($res, 1);
        if (!array_key_exists('errcode', $res)) {
            $openid = $res['openid'] ?? '';
            $user->openid = $openid;
            $user->save();
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $qr_code 邀请码
     * @param string $code 验证码
     * @param string $mobile 手机号
     * @param string $contact_phone 联系人电话
     * @param string $contact 紧急联系人
     * @param string $id_card 身份证号
     * @param string $address 通讯地址
     * @param string $nickname 姓名
     * @param string $city 城市
     * @param string $province_id 省份ID
     * @param string $city_id 城市ID
     * @param string $area_id 区县ID
     */
    public function register()
    {
        $post = $this->request->post();
        extract($post);
        if (!$nickname) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code);
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $has = Custom::where('phone', $mobile)->find();
        if ($has) {
            $apply = Apply::where('mobile', $mobile)->find();
            if (!$apply) {
                $this->error('此注册信息为客户档案，禁止注册内部小程序账号。');
            }
            if ($apply->status == 2) {
                $this->error('您提交的申述未通过!');
            }
            if ($apply->status == 0) {
                $this->error('您提交的申述正在审核中，请耐心等待。');
            }
        }

        $has = ModelUser::where('contact_phone', $contact_phone)->value('id');
        if ($has) {
            $this->error('该紧急联系人手机号已存在账号');
        }

        $has = ModelUser::where('id_card', $id_card)->value('id');
        if ($has) {
            $this->error('该身份证号已存在账号');
        }
        $has = ModelUser::where('address', $address)->value('id');
        if ($has) {
            $this->error('该联系地址已存在账号');
        }
        $acct = Admin::where('province', $province_id)->find();
        if (!$acct) {
            $this->error('该省份未绑定子平台');
        }
        if (!$province_id || !$city_id || !$area_id) {
            $this->error('地址匹配失败');
        }
        try {
            $date = [
                'qr_code' => $qr_code ?? '',
                'contact_phone' => $contact_phone ?? '',
                'contact' => $contact ?? '',
                'id_card' => $id_card ?? '',
                'address' => $address ?? '',
                'nickname' => $nickname ?? '',
                'city' => $city ?? '',
                'province_id' => $province_id ?? 0,
                'city_id' => $city_id ?? 0,
                'area_id' => $area_id ?? 0,
                'acct_id' => $acct->acct_id ?? 0,
            ];
            $ret = $this->auth->register($nickname, '',  $mobile, $date);
        } catch (\Throwable $th) {

            $this->error($th->getMessage());
        }

        if ($ret) {
            // $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     * @param string $city      城市
     * @param string $province_id 省份ID
     * @param string $city_id 城市ID
     * @param string $area_id 区县ID
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        // $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $city = $this->request->post('city');
        $province_id = $this->request->post('province_id');
        $city_id = $this->request->post('city_id');
        $area_id = $this->request->post('area_id');
        // $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        // if ($username) {
        //     $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
        //     if ($exists) {
        //         $this->error(__('Username already exists'));
        //     }
        //     $user->username = $username;
        // }
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if ($city) {
            $user->city = $city;
            $city = explode('/', $city);
            if (!$province_id || !$city_id || !$area_id) {
                $this->error('地址匹配失败');
            }
            $acct = Admin::where('province', $province_id)->find();
            if (!$acct) {
                $this->error('该省份未绑定子平台');
            }
            $user->province_id = $province_id;
            $user->city_id = $city_id;
            $user->area_id = $area_id;
            $user->acct_id = $acct->acct_id;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($user->save()) {
            Log::error('修改会员个人信息：' . var_export($user->toArray(), true));
        }
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiInternal
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }



    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 我的团队
     *
     * @ApiMethod (GET)
     * @param string $mobile      手机号
     */
    public function myTeam()
    {
        $uid = $this->auth->id;
        // $list = ModelUser::where('parent_id', $uid)->paginate();

        if ($this->request->param('mobile')) {
            $list = ModelUser::where('parent_id', $uid)->where('mobile|nickname', 'like', "%{$this->request->param('mobile')}%")->paginate(10);
        } else {
            $list = ModelUser::where('parent_id', $uid)->order('id desc')->paginate(10);
        }
        $this->success('', $list);
    }

    /**
     * 排行榜
     *
     * @ApiMethod (GET)
     * @param int $type     1=产品排行；2=业绩排行；3=收益排行
     * 
     */
    public function list()
    {
        $param = request()->param();
        extract($param);
        if ($type == 1) {
            // $ids = Order::where('status', '>', '0')->column('id');
            $list = Goods::field('id,title,CAST(sale_num AS DECIMAL(10,2)) as sale_num')->limit(5)->order('sale_num desc')->select();
            // $ids = Order::where('status', '>', '0')->column('id');
            // $idstr = implode(',', $ids);
            // $sql = "select goods.title,g.goods_id as id,CAST( sum(g.total) AS DECIMAL(10,2)) as sale_num  from (select uw.total,uw.goods_info->'$.id' as goods_id from fa_shop_ordergoods uw where uw.order_id in ({$idstr})) g left join fa_shop_goods goods on g.goods_id=goods.id group by g.goods_id order by sale_num desc limit 5";
            // $list = Db::query($sql);
        } elseif ($type == 2) {
            // $list = Order::alias('o')->join('user u', 'o.user_id=u.id', 'left')->where('o.status', '>', '0')->group('user_id')->field('u.nickname,sum(o.total_fee) as total_performance')->orderRaw('total_performance desc')->limit(5)->select();
            $list = Order::with('user')->where('order.status', '>', '0')->group('order.user_id')->field('sum(order.total_fee) as total_performance')->orderRaw('total_performance desc')->limit(5)->select();
        } else {
            $list = Commission::with('user')->where('commission.status', '1')->group('commission.user_id')->field('commission.*,sum(commission.money) as total_money')->order('total_money desc')->limit(5)->select();
        }
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @date: 2024-10-11
     * @ApiTitle (查询下级渠道商)
     * @ApiMethod (GET)
     * @ApiParams (name="type", type="integer", required=true, sample="", description="类型:1=一级渠道商,2=二级渠道商")
     * @ApiParams (name="page", type="integer", required=true, sample="", description="页码")
     * @ApiParams (name="limit", type="integer", required=true, sample="", description="每页数量")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function channel()
    {
        $params = request()->param();
        extract($params);
        $model  = new ModelUser();
        $model->where('channel', $this->auth->id);
        // if ($type == 1) {
        //     $model->where('channel_level', 1);
        // } else {
        //     $model->where('channel_level', 2);
        // $ids = ModelUser::where('channel', $this->auth->id)->column('id');
        // if ($ids) {
        //     $model->whereIn('channel', $ids);
        // } else {
        //     $model->where('id', 0);
        // }
        // }
        $list = $model->where('is_channel', 1)->order('id desc')->paginate($limit ?? 10)->toArray();
        foreach ($list['data'] as $key => &$v) {
            $today = Commission::where('user_id', $v['id'])->where('type', 'channel')->where('status', '1')->whereTime('createtime', 'today')->field('any_value(source_price) source_price')->group('order_no')->select();
            $v['today'] = round(array_sum(array_column($today, 'source_price')), 2);
            $month = Commission::where('user_id', $v['id'])->where('type', 'channel')->where('status', '1')->whereTime('createtime', 'month')->field('any_value(source_price) source_price')->group('order_no')->select();
            $v['month'] = round(array_sum(array_column($month, 'source_price')), 2);
            $total = Commission::where('user_id', $v['id'])->where('type', 'channel')->where('status', '1')->field('any_value(source_price) as source_price')->group('order_no')->select();
            $v['total'] = round(array_sum(array_column($total, 'source_price')), 2);
        }
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @ApiTitle (渠道商数据统计)
     * @ApiMethod (GET)
     * @ApiParams (name="user_id", type="integer", required=true, sample="", description="")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function channel_info()
    {
        $params = request()->param();
        extract($params);
        $uids = [];
        ModelUser::digui($user_id, $uids);
        $headcount = ModelUser::whereIn('id', $uids)->where('status', 'normal')->count();
        $monthcount = ModelUser::whereIn('id', $uids)->where('status', 'normal')->whereTime('createtime', 'm')->count();
        $todaycount = ModelUser::whereIn('id', $uids)->where('status', 'normal')->whereTime('createtime', 'd')->count();
        $xtotal = Commission::where('user_id', $user_id)->where('status', '1')->where('type', 'channel')->sum('money');
        $xtoday = Commission::where('user_id', $user_id)->where('status', '1')->where('type', 'channel')->whereTime('createtime', 'today')->sum('money');
        $xmonth = Commission::where('user_id', $user_id)->where('status', '1')->where('type', 'channel')->whereTime('createtime', 'month')->sum('money');
        $total = Commission::where('user_id', $user_id)->where('type', 'channel')->where('status', '1')->field('id,any_value(source_price) as source_price')->select();
        $total = round(array_sum(array_column($total, 'source_price')), 2);
        $today = Commission::where('user_id', $user_id)->where('type', 'channel')->where('status', '1')->whereTime('createtime', 'today')->field('any_value(source_price) source_price')->group('order_no')->select();
        $today = round(array_sum(array_column($today, 'source_price')), 2);
        $month = Commission::where('user_id', $user_id)->where('type', 'channel')->where('status', '1')->whereTime('createtime', 'month')->field('any_value(source_price) source_price')->group('order_no')->select();
        $month = round(array_sum(array_column($month, 'source_price')), 2);
        $this->success('', compact('headcount', 'monthcount', 'todaycount', 'total', 'today', 'month', 'xtotal', 'xtoday', 'xmonth'));
    }
    /**
     * @Author LK
     * @ApiTitle (渠道商管理收益)
     * @ApiMethod (GET)
     * @ApiParams (name="user_id", type="integer", required=true, sample="", description="")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function channel_earnings()
    {
        $params = request()->param();
        extract($params);
        $uids = [];
        ModelUser::digui($user_id, $uids);
        array_push($uids, $this->auth->id);
        $xtotal = Commission::whereIn('source_user_id', $uids)->where('user_id', $this->auth->id)->where('status', '1')->sum('money');
        $xtoday = Commission::whereIn('source_user_id', $uids)->where('user_id', $this->auth->id)->where('status', '1')->whereTime('createtime', 'today')->sum('money');
        $xmonth = Commission::whereIn('source_user_id', $uids)->where('user_id', $this->auth->id)->where('status', '1')->whereTime('createtime', 'month')->sum('money');
        $this->success('', compact('xtotal', 'xtoday', 'xmonth'));
    }


    /**
     * @Author LK
     * @ApiTitle (渠道商数据明细)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function channel_list()
    {
        $uid = $this->auth->id;
        $list = Commission::with(['user', 'sourceuser'])->where('user_id', $uid)->where('commission.status', '1')->where('commission.type', 'channel')->order('createtime desc')->paginate();
        $this->success('', $list);
    }

    /**
     * @Author LK
     * @date: 2024-03-15 
     * @ApiTitle (小程序二维码)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function getwxacodeunlimit()
    {
        $user = ModelUser::get($this->auth->id);
        if (!$user->qr_image) {
            $wechat = new Wechat('wxMiniProgram');
            $scene = 'code=' . $user->code;
            $response = $wechat->app_code($scene, [
                'page' => 'pages/login/register',
                'width' => 600,
                'check_path' => false,
                // 'env_version' => 'trial'
            ]);
            $save_dir = 'uploads/user';
            $filename = 'user_' . $user->id . '.png';
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $file = $response->saveAs($save_dir, $filename);
                $user->qr_image = DS . $save_dir . DS . $file;
            } else {
                $this->error('生成分享码失败');
            }
            $user->save();
        }
        $this->success('', $user);
    }

    /**
     * @Author LK
     * @date: 2024-09-29
     * @ApiTitle (子平台申请)
     * @ApiMethod (POST)
     * @ApiParams (name="name", type="integer", required=true, sample="", description="姓名")
    //  * @ApiParams (name="mobile", type="integer", required=true, sample="", description="手机号")
     * @ApiParams (name="id_num", type="integer", required=true, sample="", description="身份证")
     * @ApiParams (name="address", type="integer", required=true, sample="", description="地址")
     * @ApiParams (name="company", type="integer", required=true, sample="", description="公司")
     * @ApiParams (name="images", type="integer", required=true, sample="", description="凭证")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function apply_acct()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            ['name', 'require|max:25', '请输入姓名|姓名最多不能超过25个字符'],
            ['id_num', 'require', '请输入身份证号'],
            ['address', 'require|max:255', '请输入地址|地址最多不能超过255个字符'],
            ['company', 'require|max:255', '请输入公司|公司最多不能超过255个字符'],
            ['images', 'require', '请上传凭证'],
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

        if ($this->auth->is_channel == 0) {
            $this->error('请先成为渠道商,才可申请服务商');
        }
        $count = ModelUser::whereIn('parent_id', $this->auth->id)->where('is_channel', 1)->count();
        $direct_channel = config('site.direct_channel') ?? 0;
        if ($count < $direct_channel) {
            $this->error(sprintf('直推渠道商账号%s个,才可申请服务商', $direct_channel));
        }
        $uids = [];
        ModelUser::digui($this->auth->id, $uids);
        $total_source_price = Commission::whereIn('source_user_id', $uids)->where('status', '1')->sum('source_price');
        $total_team_sales = config('site.total_team_sales');
        if ($total_team_sales > $total_source_price) {
            $this->error(sprintf('团队总销售额不足%s元', $total_team_sales));
        }
        $params['user_id'] = $this->auth->id;
        $apply = Acctapply::get(['user_id' => $this->auth->id]);
        if ($apply) {
            if ($apply->status == 0) {
                $this->error('已提交申请，请勿重复提交');
            } elseif ($apply->status == 1) {
                $this->error('已通过申请');
            }
            $params['status'] = 0;
            $apply->isUpdate(true)->save($params);
        } else {
            Acctapply::create($params);
        }
        $this->success();
    }
    /**
     * @Author LK
     * @date: 2024-09-29
     * @ApiTitle (申请查看)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function apply_info()
    {
        $apply = Acctapply::get(['user_id' => $this->auth->id]);
        $this->responseMsg(0, $apply);
    }

    /**
     * @Author LK
     * @date: 2024-09-29
     * @ApiTitle (渠道商申请)
     * @ApiMethod (POST)
     * @ApiParams (name="channel_level", type="integer", required=true, sample="", description="1=初级,2=中级,3=高级")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function apply_channel()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            ['channel_level', 'require', '请选择申请等级'],
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        // if ($this->auth->is_channel == 1) {
        //     $this->error('你已成为渠道商');
        // }
        try {
            $pids = ModelUser::whereIn('parent_id', $this->auth->id)->column('id');
            ModelUser::digui($this->auth->id, $pids);
            $user = $this->auth->getUser();
            $total_pay_fee = Order::whereIn('user_id', $pids)->where('status', '99')->sum('pay_fee');
            $channel_level_info =  Channel::get($channel_level);
            $count = ModelUser::where('channel', $this->auth->id)->where('is_channel', 1)->count();
            if ($channel_level == 1) {
                if ($user['channel_level'] >= 1) {
                    exception('你已成为经销商');
                }
                $effective_performance = config('site.effective_performance');
                $count = Order::whereIn('user_id', $pids)->where('status', '99')->group('user_id')->field('user_id,sum(pay_fee) as total_pay_fee')->having("total_pay_fee>{$effective_performance}")->count();
                if ($total_pay_fee < $channel_level_info['team_ach']) {
                    exception(sprintf('团队总业绩%d,才可申请经销商', $channel_level_info['team_ach']));
                }
                if ($count < $channel_level_info['direct_num']) {
                    exception(sprintf('团队有效总人数%d,才可申请经销商', $channel_level_info['direct_num']));
                }
            }
            if ($channel_level == 2) {
                if ($user['channel_level'] >= 2) {
                    exception('你已成为区域或总经销商');
                }
                // $count = ModelUser::where('channel', $this->auth->id)->where('is_channel', '1')->where('channel_level', '>', 0)->count();

                if ($count < $channel_level_info['direct_num']) {
                    exception(sprintf('直推经销商%d个,才可申请区域经销商', $channel_level_info['direct_num']));
                }
                if ($total_pay_fee < $channel_level_info['team_ach']) {
                    exception(sprintf('团队总业绩%d,才可申请区域渠道商',  $channel_level_info['team_ach']));
                }
            }
            if ($channel_level == 3) {
                if ($user['channel_level'] == 3) {
                    exception('你已成为总经销商');
                }
                // $count = ModelUser::where('channel', $this->auth->id)->where('is_channel', 1)->where('channel_level', '>', 1)->count();
                if ($count < $channel_level_info['direct_num']) {
                    exception(sprintf('直推区域经销商%d个,才可申请总经销商', $channel_level_info['direct_num']));
                }
                if ($total_pay_fee < $channel_level_info['team_ach']) {
                    exception(sprintf('团队总业绩%d,才可申请总渠道商',  $channel_level_info['team_ach']));
                }
            }
            $params['user_id'] = $this->auth->id;
            $params['status'] = 0;
            $params['acct_id'] = $this->auth->acct_id;
            $apply = Channelapply::get(['user_id' => $this->auth->id, 'channel_level' => $channel_level]);
            if ($apply) {
                if ($apply->status == 0) {
                    exception('已提交申请，请勿重复提交');
                } elseif ($apply->status == 1) {
                    exception('已通过申请');
                }
                $res = $apply->isUpdate(true)->save($params);
            } else {
                $res = Channelapply::create($params, true);
            }
        } catch (\Exception $th) {
            $this->error($th->getMessage());
        }
        if ($res) {
            $this->success();
        }
        $this->error('提交失败');
    }

    /**
     * @Author LK
     * @date: 2024-09-29
     * @ApiTitle (渠道商申请查看)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function apply_channel_info()
    {
        $apply = Channelapply::get(['user_id' => $this->auth->id]);
        $this->responseMsg(0, $apply);
    }


    /**
     * 提交申述
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="integer", required=true, sample="", description="申述手机号")
     * @ApiParams (name="name", type="str", required=true, sample="", description="姓名")
     * @ApiParams (name="link_mobile", type="integer", required=true, sample="", description="联系手机号")
     * @ApiParams (name="msg", type="integer", required=true, sample="", description="内容")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    function add_apply()
    {
        $has = Apply::where('mobile', $this->request->post('mobile'))->find();
        if ($has) {
            if ($has->status == 0) {
                $this->error('已提交申请，请勿重复提交');
            }
            if ($has->status == 1) {
                $this->error('已通过申请');
            }
            $has->save([
                'name' => $this->request->post('name'),
                'link_mobile' => $this->request->post('link_mobile'),
                'msg' => $this->request->post('msg'),
                'status' => 0
            ]);
        } else {
            Apply::create([
                'mobile' => $this->request->post('mobile'),
                'name' => $this->request->post('name'),
                'link_mobile' => $this->request->post('link_mobile'),
                'msg' => $this->request->post('msg'),
                'status' => 0
            ]);
        }
        $this->responseMsg(0);
    }

    /**
     * @Author LK
     * @date: 2024-06-05 
     * @ApiTitle (实名认证)
     * @ApiMethod (POST)
     * @ApiParams (name="name", type="integer", required=true, sample="", description="姓名")
     * @ApiParams (name="id_card", type="integer", required=true, sample="", description="身份证号")
     * @ApiParams (name="real_mobile", type="integer", required=true, sample="", description="手机号")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    // public function real_user()
    // {
    //     $param = request()->param();
    //     extract($param);
    //     $validate = new Validate([
    //         ['imagex', 'require', '请上传身份证照片正面'],
    //         ['imagey', 'require', '请上传身份证照片反面'],
    //         ['base64Str', 'require', '请上传本人照片'],
    //     ]);
    //     $result = $validate->check($param);
    //     if (!$result) {
    //         $this->error($validate->getError());
    //     }
    //     try {
    //         // $resx = ModelUser::realUser(cdnurl($imagex, true), 'face');

    //         // $resx = ModelUser::realUser(cdnurl($imagex, true), 'face');
    //         // $resy = ModelUser::realUser(cdnurl($imagey, true), 'back');
    //         // if ($resx && $resy) {
    //         //     ModelUser::fxface($resx, $base64Str, $imagex, $imagey);
    //         // }
    //     } catch (\Exception $e) {
    //         $this->error($e->getMessage());
    //     }
    //     $this->success('实名已认证');
    // }
    public function real_user()
    {
        $param = request()->param();
        extract($param);
        $validate = new Validate([
            ['name', 'require', '请输入姓名'],
            ['id_card', 'require', '请输入身份证号'],
            ['real_mobile', 'require', '请输入手机号'],
        ]);
        $result = $validate->check($param);
        if (!$result) {
            $this->error($validate->getError());
        }
        try {
            ModelUser::realUser($param);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('实名已认证');
    }

    /**
     * @Author LK
     * @date: 2025-02-27 14:49:03
     * @ApiTitle (申请服务商/子公司/其他合作商)
     * @ApiMethod (POST)
     * @ApiParams (name="name", type="string", required=true, sample="", description="姓名")
     * @ApiParams (name="mobile", type="string", required=true, sample="", description="电话")
     * @ApiParams (name="address", type="string", required=true, sample="", description="地址")
     * @ApiParams (name="type", type="int", required=true, sample="", description="类别:1=服务商,2=子公司,3=其他合作商")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function apply()
    {
        $params = request()->param();
        extract($params);
        $params['user_id'] = $this->auth->id;
        Applyinfo::create($params);
        $this->success("请求成功");
    }

    /**
     * 签署协议
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="image", type="integer", required=true, sample="", description="签名图片")
     * @ApiParams (name="type", type="integer", required=true, sample="", description="1=实名认证协议2=服务商协议3=子公司协议4=其它服务商协议5=渠道商协议")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    function to_sign()
    {
        $user = $this->auth->getUser();
        // if($user->sign_image){
        //     $this->error("您已经签过了");
        // }
        $res = ModelUser::add_sign($user, $this->request->post('image'), $this->request->post('type'));
        $this->responseObj($res);
    }
}
